<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>随机点名</title>
  <link rel="stylesheet" href="css/style.css" />
  <script src="./js/vue.js"></script>
</head>

<body>
  <div id="app" class="container">

    <ul class="list clearfix">
      <li :class="{hasCover:currentIndex!==index}" @click="userClick(index)" v-for="(item,index) in list" :key="index">
        <div class="avatar">
          <img :src="item.gender===1?'img/avatar/01.jpg':'img/avatar/02.jpg'" />
        </div>
        <p>{{item.name}}</p>
      </li>
    </ul>


    <div class="fixed">
      <img class="logo" src="./img/title1.jpg">
      <div class="target-name">
        <h2>【{{current.name}}】</h3>
        <span v-if="currentIndex>-1">举手示意, 回答问题</span>
      </div>
      <img class="target-avatar" :src="current.avatar" alt="" />
      <button v-if="play" class="btn" id="btn-end" @click="stop">停止</button>
      <button v-else class="btn" id="btn-begin" @click="start">随机点名</button>
    </div>

  </div>
</body>
<script src="js/data.js"></script>
<script>
  new Vue({
    el: "#app",
    data: {
      list,
      // 需要高亮显示的用户索引
      currentIndex: -1,
      current: {
        name: "幸运用户",
        avatar: "img/head/nobody.png",
      },
      timerId: 0,
      play: false,
    },
    methods: {
      // 开始点名
      start() {
        this.timerId && clearInterval(this.timerId);
        this.timerId = setInterval(() => {
          this.currentIndex = this.getRandom(0, this.list.length - 1);
          // 更新当前用户信息
          this.setActive(this.currentIndex);
        }, 100);
        this.play = true;
      },
      stop() {
        clearInterval(this.timerId);
        this.play = false;
      },
      // 手动选择用户
      userClick(index) {
        this.stop();
        this.currentIndex = index;
        this.setActive(index);
      },
      // 设置激活用户
      setActive(index) {
        const { name, gender } = this.list[index];
        // 更新当前用户
        this.current = {
          name,
          gender,
          avatar: gender == 1 ? 'img/avatar/01.jpg' : 'img/avatar/02.jpg',
        };
      },
      // 生成指定范围的随机整数
      getRandom(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      },
    },
  });
</script>

</html>